package com.adms.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.adms.domain.Patrol;
import com.adms.domain.PatrolExample;
import com.adms.domain.PatrolExample.Criteria;
import com.adms.util.ShiroUtil;
import com.adms.domain.PatrolMapper;
import com.adms.domain.User;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;

@Transactional
@Service
public class PatrolService {
	@Autowired
	private PatrolMapper patrolMapper;

	// 根据id查询
	public Patrol getByPatrolId(Integer patrolId) {
		return patrolMapper.selectByPrimaryKey(patrolId);
	}

	// 分页查询
	public PageInfo<Patrol> list(Patrol patrol, String timeField, Date start, Date end, String orderByClause,
			String key,Boolean isSelf, Integer pageNum, Integer pageSize, Integer navigatePages) {
		PatrolExample ex = constructExample(patrol, timeField, start, end, orderByClause,isSelf);
		PageHelper.startPage(pageNum, pageSize);
		List<Patrol> patrols;
		if(StringUtil.isEmpty(key)) {
			patrols = patrolMapper.selectByExample(ex);
		}else {
			patrols = patrolMapper.selectByExampleAndKey(ex,"%"+key+"%");
		}
		return new PageInfo<>(patrols, navigatePages);
	}

	private PatrolExample constructExample(Patrol patrol, String timeField, Date start, Date end, String orderByClause,Boolean isSelf) {
		PatrolExample ex = new PatrolExample();
		Criteria or = ex.or();
		if (patrol != null) {
			Integer userId = patrol.getUserId();
			if (userId != null) {
				or.andUserIdEqualTo(userId);
			}
		}
		if (StringUtil.isNotEmpty(timeField)) {
			if (timeField.equals("creatTime")) {
				if (start != null) {
					if (end != null) {
						or.andCreateTimeBetween(start, end);
					} else {
						or.andCreateTimeGreaterThanOrEqualTo(start);
					}
				} else {
					if (end != null) {
						or.andCreateTimeLessThanOrEqualTo(end);
					}
				}
			}

		}
		if (StringUtil.isNotEmpty(orderByClause)) {
			ex.setOrderByClause(orderByClause);
		} else {
			ex.setOrderByClause("patrol.create_time desc");
		}
		if(isSelf != null && isSelf) {
			or.andUserIdEqualTo(ShiroUtil.getUser().getUserId());
		}
		return ex;
	}

	// 新增
	public boolean creat(Patrol patrol) {
		User user = ShiroUtil.getUser();
		patrol.setUserId(user.getUserId());
		patrol.setUsername(user.getUsername());
		patrolMapper.insertSelective(patrol);
		return true;
	}

	// 修改
	public boolean update(Patrol patrol) {
		patrolMapper.updateByPrimaryKeySelective(patrol);
		return true;
	}

	// 删除
	public boolean delete(int[] patrolIds) {
		if (patrolIds != null) {
			int length = patrolIds.length;
			if (length > 0) {
				if (length == 1) {
					patrolMapper.deleteByPrimaryKey(patrolIds[0]);
				} else {
					patrolMapper.deleteBatch(patrolIds);
				}
			}
		}
		return true;
	}
}
